# from GameBar.handler import register_url_handler, WebRequestHandler
from WebApps.LN_game.views.utils import json_resp
from Web.err import ErrInvalidForm, ErrOk, ErrSystem, ErrRecordNotFound
from Web.request import register_url_handler, WebRequestHandler
from ..forms import GameProgressForm
from ..models import GameProgressModel as mGameProgress


@register_url_handler(r'LN_game/progress/set/')
class SetProgress(WebRequestHandler):
    def handler(self, request, data, files, *args):
        try:
            gp = mGameProgress.objects.get(uid=int(data['uid']), gid=int(data['gid']))
        except:
            gp = None

        try:
            progress = GameProgressForm(data, instance=gp)
            if not progress.is_valid():
                return json_resp(ErrInvalidForm())

            progress.save(True)
            return json_resp(ErrOk())
        except Exception as e:
            return json_resp(ErrSystem(e.message))


@register_url_handler(r'LN_game/progress/get/')
class GetProgress(WebRequestHandler):
    def handler(self, request, data, files, *args):
        try:
            gp = mGameProgress.objects.get(uid=int(data['uid']), gid=int(data['gid']))
            return json_resp(ErrOk(), {"progress": gp.progress, "time": gp.time})
        except mGameProgress.DoesNotExist:
            return json_resp(ErrRecordNotFound())